package com.rt.java.util.concurrent;

import lombok.Data;
import lombok.SneakyThrows;

import java.time.LocalTime;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class AtomicBooleanDemo {
    public static void main(String[] args) throws InterruptedException {
        ABRunnable abRunnable = new ABRunnable();
        new Thread(abRunnable).start();
        TimeUnit.SECONDS.sleep(3);
        abRunnable.stop();


    }
}

@Data
class ABRunnable implements Runnable {

    private AtomicBoolean ab = new AtomicBoolean(true);

    @SneakyThrows
    @Override
    public void run() {
        System.out.println(LocalTime.now());
        while (ab.get()) {
            System.out.println("do something");
            TimeUnit.SECONDS.sleep(1);
        }
        System.out.println(LocalTime.now());
    }

    public void stop() {
        ab.compareAndSet(true, false);
    }
}
